import {
  ActionType,
  ModalForm,
  PageContainer,
  ProCard,
  ProColumns,
  ProFormDigit,
  ProFormText,
  ProTable
} from "@ant-design/pro-components";
import {Button, Form, message, Tooltip} from "antd";
import React, {useRef, useState} from "react";
import {EditOutlined, PlusOutlined, SettingFilled, UnorderedListOutlined} from "@ant-design/icons";
import {globalApi, handleGloblApi} from "@/services/admin-api/globalApi";

type DictType = {
  dtId: number;
  dtName: string;
  dtCode: string;
  delFlag: boolean;
  createTime: string;
  createUserId: number;
  createUserName: string;
  updateTime: string;
  updateUserId: number;
  updateUserName: string;
};

type DictList = {
  dlId: number;
  dtCode: string;
  dlLabel: string;
  dlValue: number;
  delFlag: boolean;
  createTime: string;
  createUserId: number;
  createUserName: string;
  updateTime: string;
  updateUserId: number;
  updateUserName: string;
};

export default () => {

  const [modalOpen, handleModalOpen] = useState(false);
  const [modalDictListOpen, handleDictListModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [dlForm] = Form.useForm();
  const actionRef = useRef<ActionType>();
  const actionDlRef = useRef<ActionType>();
  const [dtCode, setDtCode] = useState('');
  // const [currentRow, setCurrentRow] = useState<ProductType>();

  const columns: ProColumns<DictType>[] = [
    // {title: '', valueType: 'indexBorder'},
    {title: 'dtId', dataIndex: 'dtId', valueType: 'digit', hideInSearch: true,},
    {title: 'dtName', dataIndex: 'dtName', valueType: 'text'},
    {title: 'dtCode', dataIndex: 'dtCode', valueType: 'text'},
    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
    {
      title: <SettingFilled/>,
      render: (_, record) => [
        <Tooltip title={"编辑"} key={'edit_' + record.dtId}>
          <Button
            size="small" icon={<EditOutlined/>} type="primary"
            onClick={async () => {
              form.setFieldsValue({...record});
              handleModalOpen(true);
            }}
          />
        </Tooltip>,
        <Tooltip title={"字典数据"} key={'listdl_' + record.dtId}>
          <Button
            size="small" icon={<UnorderedListOutlined/>} type="primary"
            onClick={async () => {
              // form.setFieldsValue({...record});
              // handleModalOpen(true);
              setDtCode(record.dtCode)
            }}
          />
        </Tooltip>,
        <Tooltip title={"新增字典数据"} key={'adddl_' + record.dtId}>
          <Button
            size="small" icon={<PlusOutlined/>} type="primary"
            onClick={async () => {
              setDtCode(record.dtCode)
              handleDictListModalOpen(true)
            }}
          />
        </Tooltip>,
      ],
      valueType: 'option',
    },
  ];

  const dlColumns: ProColumns<DictList>[] = [
    // {title: '', valueType: 'indexBorder'},
    {title: 'dlId', dataIndex: 'dlId', valueType: 'digit'},
    {title: 'dtCode', dataIndex: 'dtCode', valueType: 'text'},
    {title: 'dlLabel', dataIndex: 'dlLabel', valueType: 'text'},
    {title: 'dlValue', dataIndex: 'dlValue', valueType: 'digit'},
    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
    {
      title: <SettingFilled/>,
      render: (_, record) => [
        <Tooltip title={"新增"} key={'dledit_' + record.dlId}>
          <Button
            size="small" icon={<EditOutlined/>} type="primary"
            onClick={async () => {
              dlForm.setFieldsValue({...record});
              handleDictListModalOpen(true);
            }}
          /></Tooltip>,
      ],
      valueType: 'option',
    },
  ];

  return <PageContainer header={{title: '', breadcrumb: {},}}>
    <ProCard
      split={'vertical'} bordered headerBordered>
      <ProCard colSpan="50%">
        <ProTable<DictType>
          columns={columns} actionRef={actionRef}
          // search={{span: 4}}
          headerTitle={
            <Tooltip title={"新增"}>
              <Button
                key="primary" type="primary" icon={<PlusOutlined/>} onClick={() => {
                handleModalOpen(true)
              }}/>
            </Tooltip>
          }
          request={async (param) => {
            console.log('param = ', param)
            const hide = message.loading('正在加载表格');
            const r = await globalApi('/sys/dictTypeTable', param)
            console.log('r = ', r)
            hide();
            message.success('Loading successfully');
            return {success: r.success, data: r.data.data, total: r.data.total}
          }} rowKey={(record) => record.dtId}
          columnsState={{
            defaultValue: {
              delFlag: {show: false},
              createUserId: {show: false},
              updateUserId: {show: false}
            }
          }}/>
      </ProCard>
      <ProCard>
        <ProTable<DictList>
          columns={dlColumns} actionRef={actionDlRef} search={false} params={{dtCode}}
          request={async (param) => {
            console.log('param = ', param)
            if (param.dtCode === '') {
              return {success: true, data: [], total: 0}
            }
            const hide = message.loading('正在加载表格');
            const r = await globalApi('/sys/dictListTable', param)
            console.log('r = ', r)
            hide();
            message.success('Loading successfully');
            return {success: r.success, data: r.data.data, total: r.data.total}
          }} rowKey={(record) => record.dlId}
          columnsState={{
            defaultValue: {
              delFlag: {show: false},
              createUserId: {show: false},
              updateUserId: {show: false}
            }
          }}/>
      </ProCard>
    </ProCard>

    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="400px" open={modalOpen} onOpenChange={handleModalOpen} form={form}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/sys/dictTypeSaveOrUpdate', value)

        if (success) {
          actionRef.current?.reload();
          return true
        }

      }}
    >
      <ProFormDigit label="dtId" name="dtId" hidden/>
      <ProFormText label="dtName" rules={[{required: true}]} name="dtName"/>
      <ProFormText label="dtCode" rules={[{required: true}]} name="dtCode"/>
    </ModalForm>

    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="400px" open={modalDictListOpen} onOpenChange={handleDictListModalOpen} form={dlForm}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/sys/dictListSaveOrUpdate', value)

        if (success) {
          actionDlRef.current?.reload();
          return true
        }

      }}
    >
      <ProFormDigit label="dlId" name="dlId" hidden/>
      <ProFormText label="dtCode" rules={[{required: true}]} disabled initialValue={dtCode} name="dtCode"/>
      <ProFormText label="dlLabel" rules={[{required: true}]} name="dlLabel"/>
      <ProFormDigit label="dlValue" rules={[{required: true}]} name="dlValue"/>
    </ModalForm>

  </PageContainer>
}
